<template>
	<view class="page-container">
		<!-- 主内容区 -->

		<view class="main-container">
			<!-- 查询条件区域 -->
			<u-picker :show="show" :columns="columns" keyName="admdivName" :defaultIndex=[3] @cancel='show=false'
				@confirm="handleProvinceChange">
			</u-picker>
			<u-datetime-picker :show="showMonth" mode="year-month" @cancel='showMonth=false' v-model="dateVal"
				@confirm="handleMonthChange">
			</u-datetime-picker>
			<view id="toggleBox" class="query-box"
				:style="{ height: expanded ? '400rpx' : '50rpx', overflow: 'hidden' }">
				<view class="query-title" @click="toggleBoxHeight">
					<u-icon name="search" color="#165DFF" size="24" class="icon-mr"></u-icon>
					<text class="title-text">查询条件</text>
				</view>

				<view class="query-content">
					<view class="form-grid">
						<!-- 省份选择 -->
						<view class="form-item">
							<view class="form-label">省份:</view>
							<view class="province-select" @click="show=true">
								<view>
									{{selectedProvince.admdivName}}
								</view>
								<u-icon name="arrow-down" size="16"></u-icon>
							</view>
						</view>
						<!-- 报销单位 -->
						<view class="form-item">
							<view class="form-label">报销单位:</view>
							<view class="province-select" @click="goReimbursementUnit">
								<view>
									{{companyObj.agencyName}}
								</view>
								<u-icon name="arrow-down" size="16"></u-icon>
							</view>
						</view>

						<!-- 报销月份 -->
						<view class="form-item">
							<view class="form-label">报销月份:</view>
							<view class="province-select" @click="showMonth=true">
								<view>
									{{selectedMonth}}
								</view>
								<u-icon name="arrow-down" size="16"></u-icon>
							</view>
						</view>
					</view>

					<!-- 按钮区域 -->
					<view class="btn-group">
						<u-button text="查询" type="primary" size="small" class="query-btn"
							@click="handleQuery"></u-button>
						<u-button text="重置" type="default" class="reset-btn" size="small"
							@click="handleReset"></u-button>
					</view>
				</view>
			</view>

			<!-- 记录列表区域 -->
			<view class="record-list">
				<!-- 列表内容 -->
				<scroll-view :style="{ height: expanded ? 'calc(100vh - 500rpx)' : 'calc(100vh - 150rpx)' }" scroll-y
					:scroll-with-animation="true">
					<view class="list-item" v-for="(item, index) in recordList" :key="index" >
						<view class="item-content">
							<!-- 报销单位 -->
							<view class="content-item col-3">
								<text class="label ">报销单位：</text>
								<text class="value">{{ item.authorizedPartyName }}</text>
							</view>
							<!-- 报销人 -->
							<view class="content-item col-3">
								<text class="label ">报 销 人：</text>
								<text class="value">{{ item.payerPartyName }}</text>
							</view>
							<!-- 授权批次 -->
							<view class="content-item col-2">
								<text class="label ">授权批次：</text>
								<text class="value">{{ item.authorizeId }}</text>
							</view>

							<!-- 授权时间 -->
							<view class="content-item col-3">
								<text class="label ">授权时间：</text>
								<text class="value">{{ formatDate(item.authorizeDate)}} {{item.authorizeTime}}</text>
							</view>

							<!-- 报销状态 -->
							<view class="content-item col-2">
								<text class="label ">报销状态：</text>
								<view class="status-tag"
									:class="item.accstate == '1' ? 'status-success' :'status-danger'">

									<view class="status-dot"></view>
									<text class="status-text">{{ item.accstate == '1' ? '已报销' :'未报销' }}</text>
								</view>
							</view>
							<!-- 报销状态 -->
							<view class="content-item col-2">
								<text class="label ">授权状态：</text>
								<view class="status-tag"
									:class="item.resultCode == '02' ? 'status-success' : (item.resultCode == '01' ? 'status-warning' : (item.resultCode == '03' ? 'status-danger' : (item.resultCode == '04' ? 'status-gray' : '')))">
							
									<view class="status-dot"></view>
									<text class="status-text">{{ item.resultCode == '02' ? '已确认' : (item.resultCode == '01' ? '待确认' : (item.resultCode == '03' ? '已拒收' : (item.resultCode == '04' ? '已撤销' : ''))) }}</text>
								</view>
							</view>
							<view class="detail-box">
								<u-button text="详情" icon="file-text" size="small"  type="primary" :plain="true" @click="searchDetail(item)"></u-button>
							</view>
							<!-- 操作列 -->
							<view class="content-item col-2 operate-area">
								<u-button text="催办" icon="bell" size="small" :disabled="item.accstate==1||item.resultCode == '03'||item.resultCode == '04'" type="primary"
									:plain="true" @click="showReminderModal(item)"></u-button>
								<u-button text="撤销" icon="reload" size="small" type="primary" :plain="true"
									:disabled="item.resultCode!='01'" @click="showRevokeModal(item)"></u-button>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 催办确认弹窗 -->
		<u-modal :show="reminderModalVisible" title="确认催办" :show-cancel-button="true" cancel-text="取消"
			confirm-text="确认催办" @confirm="confirmReminder" @cancel="reminderModalVisible = false">
			<view class="modal-content">
				<text>确定要向该单位发送催办通知吗？</text>
			</view>
		</u-modal>

		<!-- 撤销确认弹窗 -->
		<u-modal :show="revokeModalVisible" title="确认撤销" :show-cancel-button="true" cancel-text="取消" confirm-text="确认撤销"
			confirm-color="#F53F3F" @confirm="confirmRevoke" @cancel="revokeModalVisible = false">
			<view class="modal-content">
				<text>确定要撤销该授权记录吗？此操作不可恢复。</text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		showProvince,
	} from '@/api/api.js'
	import {
		queryAuthorizeList,
		handleUrge,
		cancelAuthorize,
		queryAuthorize
	} from '@/api/expenceApi.js'
	export default {
		data() {
			return {
				show: false,
				// 查询条件相关
				dateVal: Number(new Date()),
				showMonth: false,
				expanded: false,
				companyObj: {
					agencyName:'请输入报销单位'
				},
				selectedMonth: '请选择报销月份',
				// 省份列表
				columns: [], //格式为[[]]
				selectedProvince: {
					admdivName: '河北省',
					admdivCode: '130000'
				},
				// 列表数据
				recordList: [],

				// 弹窗控制
				reminderModalVisible: false,
				revokeModalVisible: false,
				currentObj:{},
			};
		},
		async created() {
			await this.showProvinceFun()
			await this.conversionDate()
			await this.handleQuery()
		},
		onLoad() {
			uni.$on('selectedUnit', (data) => {
				console.log('shenme', data);
				this.companyObj = data
			})
		},
		methods: {
			formatDate(str) {
			  // 检查输入格式是否正确（8位数字）
			  if (!/^\d{8}$/.test(str)) {
			    throw new Error('请输入正确的8位日期字符串，如"20251025"');
			  }
			  // 提取年、月、日
			  const year = str.substring(0, 4);
			  const month = str.substring(4, 6);
			  const day = str.substring(6, 8);
			  // 拼接成目标格式
			  return `${year}-${month}-${day}`;
			},
			async searchDetail(item){
				console.log('详情',item)
				uni.showLoading({
					title:'加载中'
				})
				const res =await queryAuthorize({
					authorizeId:item.authorizeId,
					authorizerAcctId:item.authorizedAcctId
				})
				if(res.result==0){
					uni.hideLoading()
					uni.navigateTo({
						url: '/pages/expense/expenseDetail?item=' + encodeURIComponent(JSON.stringify(res.singleData))
					})
				}else{
					uni.hideLoading()
					this.$u.toast(res.message || '接口错误');
				}
			},
			goReimbursementUnit(){
				uni.navigateTo({
					url:'/pages/home/reimbursementUnit'
				})
			},
			async showProvinceFun() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await showProvince()
				if (res.result == 0) {
					this.columns[0] = res.data
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},
			// 省份变化处理
			handleProvinceChange(e) {
				this.show = false
				console.log('===', e)
				this.selectedProvince = e.value[0]
			},
			// 切换查询条件框高度
			toggleBoxHeight() {
				this.expanded = !this.expanded;
			},
			handleMonthChange(e) {
				this.showMonth = false;
				// e.value 是时间戳
				const date = new Date(e.value);
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				this.selectedMonth = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('选择的月份:', this.selectedMonth);
			},
			async conversionDate() {
				const date = new Date();
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const nowDate = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('===', nowDate)
				this.selectedMonth = nowDate
			},
			// 处理查询
			async handleQuery() {
				// 实现查询逻辑
				uni.showLoading({
					title: '查询中'
				})
				const [year, month] = this.selectedMonth.split('-')
				const params={
					supervisorAreaCode:this.selectedProvince.admdivCode.substring(0, 2),
					authorizedAcctId:this.companyObj.accountId,
					authorizeDate:year+month,
				}
				const res = await queryAuthorizeList(params)
				console.log('res',res)
				if(res.result==0){
					this.recordList=res.data
					uni.hideLoading()
				}else{
					uni.hideLoading()
					this.$u.toast(res.message || '接口错误');
				}
				
			},

			// 处理重置
			handleReset() {
				this.selectedProvince = {},
					this.companyObj = {};
				this.selectedMonth = '';
			},

			// 显示催办弹窗
			showReminderModal(item) {
				this.reminderModalVisible = true;
				this.currentObj=item
			},

			// 显示撤销弹窗
			showRevokeModal(item) {
				this.revokeModalVisible = true;
				this.currentObj=item
			},

			// 确认催办
			async confirmReminder() {
				// 实现催办逻辑
				console.log('确认催办');
				uni.showLoading({
					title: '查询中'
				})
				const res = await handleUrge({
					authorizeId:this.currentObj.authorizeId
				})
				console.log('res',res)
				if(res.result==0){
					uni.hideLoading()
					this.reminderModalVisible = false;
					this.$u.toast(res.message || '催办成功');
					this.handleQuery()
				}else{
					uni.hideLoading()
					this.$u.toast(res.message || '接口错误');
				}
			},

			// 确认撤销
			async confirmRevoke() {
				// 实现撤销逻辑
				console.log('确认撤销');
				// 这里可以添加提示信息
				uni.showLoading({
					title: '查询中'
				})
				const res = await cancelAuthorize({
					authorizeId:this.currentObj.authorizeId
				})
				console.log('res',res)
				if(res.result==0){
					uni.hideLoading()
					this.revokeModalVisible = false;
					this.$u.toast(res.message || '撤销成功');
					this.handleQuery()
				}else{
					uni.hideLoading()
					this.$u.toast(res.message || '接口错误');
				}
			}
		}
	};
</script>

<style scoped>
	.province-select {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 80%;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		height: 40rpx;
		padding: 10rpx;
		font-size: 14px;
		/* 120px -> 180rpx */
	}

	/* 基础样式 */
	.page-container {
		background-color: #F2F3F5;
		min-height: 100vh;
		font-size: 28rpx;
		color: #1D2129;
	}

	/* 头部样式 */
	.header {
		display: flex;
		background-color: #fff;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 24rpx;
		border-bottom: 1px solid #eee;
	}

	.back-btn {
		font-size: 36rpx;
		color: #000;
		text-decoration: none;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
	}
	.detail-box{
		position: absolute;
		top: 10rpx;
		right: 10rpx;
	}
	/* 主内容区 */
	.main-container {
		padding: 20rpx 24rpx;
	}

	/* 查询条件区域 */
	.query-box {
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
		padding: 20rpx;
		margin-bottom: 20rpx;
		transition: height 0.3s ease;
	}

	.query-title {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #1D2129;
		margin-bottom: 20rpx;
	}

	.icon-mr {
		margin-right: 10rpx;
	}

	.query-content {
		padding-top: 10rpx;
	}

	.form-grid {
		display: grid;
		grid-template-columns: 1fr;
		gap: 24rpx;
	}

	@media (min-width: 768px) {
		.form-grid {
			grid-template-columns: repeat(3, 1fr);
		}
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.form-label {
		width: 120rpx;
		font-size: 26rpx;
		color: #4E5969;
	}

	.form-control {
		flex: 1;
		height: 40rpx;
		border-radius: 8rpx;
		font-size: 14px;
	}

	.navigator-wrap {
		flex: 1;
	}

	.btn-group {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		padding-top: 20rpx;
	}

	.query-btn {
		width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #165DFF;
	}

	.reset-btn {
		width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #F2F3F5;
		color: #4E5969;
	}

	/* 记录列表区域 */
	.record-list {


		overflow: hidden;
	}

	.list-header {
		display: flex;
		background-color: #F2F3F5;
		padding: 20rpx 24rpx;
		font-size: 24rpx;
		color: #4E5969;
		border-bottom: 1px solid #E5E6EB;
	}

	.header-item {
		font-weight: 500;
	}

	.col-2 {
		flex: 2;
	}

	.col-3 {
		flex: 3;
	}


	.list-item {
		position: relative;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
	}

	.list-item:last-child {
		border-bottom: none;
	}

	.item-content {
		padding: 24rpx;
	}

	.content-item {
		margin-bottom: 16rpx;
	}

	.content-item:last-child {
		margin-bottom: 0;
	}

	.label {
		display: inline-block;
		width: 120rpx;
		font-size: 24rpx;
		color: #4E5969;
		margin-right: 8rpx;
	}

	.value {
		font-size: 26rpx;
		color: #1D2129;
	}

	/* 状态标签 */
	.status-tag {
		display: inline-flex;
		align-items: center;
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
	}

	.status-dot {
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
		margin-right: 8rpx;
	}

	.status-success {
		background-color: rgba(0, 180, 42, 0.1);
		color: #00B42A;
	}

	.status-success .status-dot {
		background-color: #00B42A;
	}

	.status-warning {
		background-color: rgba(255, 125, 0, 0.1);
		color: #FF7D00;
	}

	.status-warning .status-dot {
		background-color: #FF7D00;
	}

	.status-danger {
		background-color: rgba(245, 63, 63, 0.1);
		color: #F53F3F;
	}

	.status-danger .status-dot {
		background-color: #F53F3F;
	}

	.status-gray {
		background-color: rgba(229, 230, 235, 0.5);
		color: #4E5969;
	}

	.status-gray .status-dot {
		background-color: #86909C;
	}

	/* 操作区域 */
	.operate-area {
		display: flex;
		justify-content: flex-end;
		gap: 10rpx;
	}

	.operate-btn {
		color: #165DFF;
		background-color: transparent;
		padding: 0 10rpx;
		height: 50rpx;
		line-height: 50rpx;
	}

	.operate-btn.disabled {
		color: #86909C;
	}

	/* 弹窗内容 */
	.modal-content {
		padding: 20rpx 0;
		font-size: 26rpx;
		color: #4E5969;
	}

	/* 响应式样式 */
	@media (min-width: 768px) {
		.hidden-md {
			display: flex;
		}

		.show-md {
			display: none;
		}

		.content-item {
			margin-bottom: 0;
		}
	}

	@media (max-width: 767px) {
		.hidden-md {
			display: none;
		}

		.show-md {
			display: inline;
		}

		.content-item {
			width: 100%;
		}
	}
</style>